<?php

namespace Lib\Service;

use Lib\Cache\RedisAction;

class Lock
{
    private $redis;

    public function __construct()
    {
        $this->redis = new RedisAction();
    }

    /**
     * 获取lock
     * @param string 要获取锁定的key
     * @param int    需要加锁最长时间
     * @return bool true:成功获取锁，可以进行后续操作， false-获取锁失败，终止后续操作
     */
    public function getLock($sKey, $time = 3)
    {
        return $this->redis->set($sKey, time(), ['nx', 'ex' => $time]);
    }

    /**
     * 释放lock
     * @param string $sKey 要释放的lock在redis中对应的key
     * @return bool
     */
    public function delLock($sKey)
    {
        $iLoop = 3;
        do {
            $iKeys = $this->redis->del($sKey);
        } while ((--$iLoop) && !$iKeys);

        return true;
    }
}
